package br.ufal.ic.sd.mom.cliente.threadcliente;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;

import br.ufal.ic.sd.mom.cliente.core.TratadorMensagemEntrada;
import br.ufal.ic.sd.mom.cliente.util.Configurador;

/**
 * @author keven lenisk almeida andarde
 * 
 */
public class AgenteReceptor extends ThreadCliente {

	private ServerSocket serverSocket;
	private Socket socket;
	private ObjectInputStream in;
	private ObjectOutputStream out;
	private TratadorMensagemEntrada tratadorMensagemEntrada;

	public AgenteReceptor(TratadorMensagemEntrada mensagem) {

		this.tratadorMensagemEntrada = mensagem;

		try {
			this.serverSocket = new ServerSocket(Integer.parseInt(Configurador.getValor(Configurador.PORTA_LOCAL)));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void run() {

		try {
			this.socket = this.serverSocket.accept();
			this.socket.setSoTimeout(300);
			this.out = new ObjectOutputStream(this.socket.getOutputStream());
			this.out.flush();
			this.in = new ObjectInputStream(this.socket.getInputStream());

		} catch (IOException e) {
			e.printStackTrace();
		}

		while (true) {

			try {
				String t = in.readObject().toString();
				this.tratadorMensagemEntrada.add(t);
			} catch (IOException e) {
				continue;
			} catch (ClassNotFoundException e) {
				continue;
			}

		}

	}

	@Override
	public void encerrarConexao() {

		try {
			this.socket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
